package com.ruoyi.deviceLog.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.device.domain.Device;
import com.ruoyi.device.mapper.DeviceMapper;
import com.ruoyi.deviceLog.domain.DeviceLog;
import com.ruoyi.deviceLog.service.DeviceLogService;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 公司设备日常检查记录Controller
 *
 * @author zjh
 * @date 2022-05-10
 */
@Controller
@RequestMapping("/log")
public class DeviceLogController extends BaseController {
    private String prefix = "deviceLog";

    @Autowired
    private DeviceLogService deviceLogService;

    @Autowired
    private DeviceMapper deviceMapper;

    public static void main(String[] args) {


    }

    @RequiresPermissions("business:log:view")
    @GetMapping()
    public String log() {
        return prefix + "/deviceLog";
    }

    /**
     * 查询公司设备日常检查记录列表
     */
    @RequiresPermissions("business:log:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam(value = "beginTime", required = false) String beginTime, @RequestParam(value = "endTime", required = false) String endTime
    ) {
        DeviceLog deviceLog1 = new DeviceLog();
        deviceLog1.setBeginTime(beginTime);
        deviceLog1.setEndTime(endTime);
        Long companyId = SecurityUtils.getLoginUser().getCompanyId();
        deviceLog1.setCompanyId(companyId);

        //查询设备设施管理
        List<Device> devices = deviceMapper.selectDeviceForLog(companyId);
        //查询公司设备日常检查记录列表
        List<DeviceLog> deviceLogs = deviceLogService.selectDeviceLogByComId(deviceLog1);

        startPage();
        //查询公司设备日常检查记录列表（根据创建时间分组，用于获取当前的时间获取时间）
        List<DeviceLog> deviceLogs2 = deviceLogService.selectDeviceLogByComIds(deviceLog1);

        List<Date> dataList = new ArrayList<>();

        for (DeviceLog deviceLog : deviceLogs2) {
            Date data = deviceLog.getCreateTime();
            if (dataList.contains(data)) {
                continue;
            } else {
                dataList.add(data);
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 列表数据
        List<Map<String, Object>> reData = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < dataList.size(); i++) {
            Map<String, Object> midMap = new HashMap<>();
            Date time = dataList.get(i);
            midMap.put("dateTime", sdf.format(dataList.get(i)));
            for (Device device : devices) {
                Long deviceId = device.getDeviceId();
                for (DeviceLog deviceLog : deviceLogs) {
//                        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
//                        sdf.applyPattern("yyyy-MM-dd HH:mm:ss");// a为am/pm的标记
                    Date nowTime = deviceLog.getCreateTime();
//                        String data=sdf.format(nowTime);
                    Long deviceLogDId = deviceLog.getDeviceId();
                    if (deviceId.equals(deviceLogDId) && nowTime.equals(time)) {
                        midMap.put(deviceLogDId.toString(), deviceLog.getDeviceStatus());
                    }
                }
            }
            reData.add(midMap);
        }

        long total = getDataTable(deviceLogs2).getTotal();

        return getDataTable2("", reData, total);
//        return getDataTable(reData);
    }

    /**
     * 重写分页数据
     *
     * @param msg  提示信息
     * @param list 数据
     * @return 结果
     */
    protected TableDataInfo getDataTable2(String msg, List<Map<String, Object>> list, Long deviceLog) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setRows(list);
        rspData.setTotal(deviceLog);
        return rspData;
    }

    /**
     * 查询项目列表
     */
//    @RequiresPermissions("school:items:list")
    @PostMapping("/itemlist")
    @ResponseBody
    public String selectItemList() {
        Long companyId = SecurityUtils.getLoginUser().getCompanyId();
        DeviceLog deviceLog1 = new DeviceLog();
        deviceLog1.setCompanyId(companyId);
        List<Device> devices = deviceMapper.selectDeviceForLog(companyId);
        List<DeviceLog> deviceLogs = deviceLogService.selectDeviceLogByComId(deviceLog1);
        List<Date> dataList = new ArrayList<>();

        Map<Integer, List<String>> map = new HashMap<>();

        for (DeviceLog deviceLog : deviceLogs) {
            Date data = deviceLog.getCreateTime();
            if (dataList.contains(data)) {
                continue;
            } else {
                dataList.add(data);
            }
        }
        // 表格的头
        Map<String, Object> titleMap = new LinkedHashMap<>();
        // 列表数据
        List<Map<String, Object>> reData = new ArrayList<Map<String, Object>>();
        for (int i = 0; i < dataList.size(); i++) {
            if (i == 0) {
                titleMap.put("dateTime", "日期");
            }
            Map<String, Object> midMap = new HashMap<>();
            midMap.put("dateTime", dataList.get(i));
            for (Device device : devices) {
                Long deviceId = device.getDeviceId();
                String deviceName = device.getDeviceItem();
                if (i == 0) {
                    titleMap.put(deviceId.toString(), deviceName);
                }
            }
            reData.add(midMap);
        }
        String data = null;

        //处理数据 - 转为json字符串
        if (devices.size() > 0) {
            data = JSON.toJSONString(devices);
        }
        JSONObject jsonobject = new JSONObject();
        jsonobject.put("titleData", titleMap);
        jsonobject.put("reData", reData);
        //处理数据 - 封装返回数据
        jsonobject.put("result", "1");
        jsonobject.put("info", "");
        jsonobject.put("data", null == data ? "" : data);
        return jsonobject.toString();
    }


    /**
     * 导出公司设备日常检查记录列表
     */
    @RequiresPermissions("business:log:export")
    @PostMapping("/export")
    @ResponseBody
    public void exportTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 公司设备日常检查记录
        String s = deviceLogService.exportTemp();
        String downloadName = StringUtils.substringAfterLast(s, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(s, response.getOutputStream());
        FileUtils.deleteFile(s);
    }

    /**
     * 新增公司设备日常检查记录
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存公司设备日常检查记录
     */
    @RequiresPermissions("business:log:add")
    @Log(title = "公司设备日常检查记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave() {
        return toAjax(deviceLogService.insertDeviceLog());
    }

    /**
     * 修改公司设备日常检查记录
     */
    @GetMapping("/edit/{logId}")
    public String edit(@PathVariable("logId") Long logId, ModelMap mmap) {
        DeviceLog deviceLog = deviceLogService.selectDeviceLogById(logId);
        mmap.put("deviceLog", deviceLog);
        return prefix + "/edit";
    }

    /**
     * 修改保存公司设备日常检查记录
     */
    @RequiresPermissions("business:log:edit")
    @Log(title = "公司设备日常检查记录", businessType = BusinessType.UPDATE)
    @GetMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(String dateTime, String key, String status) throws ParseException {
        return toAjax(deviceLogService.updateDeviceLog(dateTime, key, status));
    }

    /**
     * 删除公司设备日常检查记录
     */
    @RequiresPermissions("business:log:remove")
    @Log(title = "公司设备日常检查记录", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(deviceLogService.deleteDeviceLogByIds(ids));
    }
}
